package com.cloudcc.boot.utils.demo;

import com.cloudcc.boot.model.UserInfo;
import com.cloudcc.boot.utils.util.CCService;
import com.cloudcc.boot.utils.util.MD5;
import com.cloudcc.boot.utils.util.OperationService;
import com.cloudcc.client.CCObject;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * 林贵美 2019-03-18创建
 * 类名：QuoteVerification
 * 相关bug：354 报价单提交MC校验逻辑
 *
 * 1.提交报价时，校验报价单明细列表中是否有含MC货品，但是没有选择对应MC的报价明细，
 *   如果有，则给出提示“您提交的报价清单中有含MC的货品，您还未选择MC信息，是否继续提交报价”如果选择是，则更新对应的字段“报价提交状态”为勾选状态
 *
 * 2.提交报价时，校验是否有mc服务，如果没有MC，但是填写了免印信息，不允许提交报价
 *
 * 以上逻辑也适用于：打印报价单按钮，特价申请按钮
 **/
public class QuoteVerification {
    private CCService cs ;
	private UserInfo userInfo;
	private Logger logger;
	public QuoteVerification(UserInfo userInfo){
		cs = new CCService(userInfo);
		this.userInfo = userInfo;
		logger = LoggerFactory.getLogger(QuoteVerification.class);
	}
    
    /**
     * 林贵美 2019-03-18创建
     * 方法名：verification
     * 校验报价单明细列表中：套类产品的对应主机是否有含MC货品，但是没有选择对应MC的报价明细，
     * 如果有，则给出提示“您提交的报价清单中有含MC的货品，您还未选择MC信息，是否继续提交报价”
     **/
    public String verification(String bjdID) throws Exception {
        String yzSql = " select p.mcflg as pmcflg,q.mcid,q.chanpin as qchanpin,p.recordtype as precordtype ";
               yzSql+= " from quotedetail q, product p ";
               yzSql+= " where q.chanpin=p.id and ";
               yzSql+= "       q.is_deleted='0' and ";
               yzSql+= "       p.is_deleted='0' and ";
               yzSql+= "       q.bjdmc='"+bjdID+"' and ";
               yzSql+= "       q.mcid is null ";
               
        String fhjg = "";
        logger.info(yzSql);
        List<CCObject> quotedetailList = cs.cqlQuery("quotedetail", yzSql);//报价单明细
        for (int q=0;q<quotedetailList.size();q++) {
            String qchanpin = quotedetailList.get(q).get("qchanpin")==null?"":quotedetailList.get(q).get("qchanpin").toString();//货品
            String pmcflg = quotedetailList.get(q).get("pmcflg")==null?"":quotedetailList.get(q).get("pmcflg").toString();//是否含MC
            String precordtype = quotedetailList.get(q).get("precordtype")==null?"":quotedetailList.get(q).get("precordtype").toString();//记录类型
            if ("20181970E95B43CjCYcE".equals(precordtype)) {
                String cpzsjSql = " select t.price as tprice, t.productcodes as tproductcodes,p.typeofgoods as ptypeofgoods ";
                       cpzsjSql+= " from tlcphmxcpddyb t,product p  ";
                       cpzsjSql+= " where t.is_deleted='0' and p.is_deleted='0' and t.productcodes=p.id and ";
                       cpzsjSql+= "       t.genus='"+qchanpin+"' and p.mcflg='是' ";
                logger.info(cpzsjSql);
                List<CCObject> tlcphmxcpddybListzj=cs.cqlQuery("tlcphmxcpddyb",cpzsjSql+"  and p.typeofgoods='主机' ");//套类产品主数据
                if (tlcphmxcpddybListzj.size() > 0) {
                    fhjg = "您提交的报价清单中有含MC的货品，您还未选择MC信息，是否继续提交报价";
                    logger.info(fhjg);
                }
            } else {
                if ("是".equals(pmcflg)) {
                    fhjg = "您提交的报价清单中有含MC的货品，您还未选择MC信息，是否继续提交报价";
                    logger.info(fhjg);
                }
            }
        }
        return fhjg;
    }
    
    /**
     * 林贵美 2019-03-18创建
     * 方法名：mcyzJy
     * 校验是否有mc服务，如果没有MC，但是填写了免印信息，不允许提交报价
     **/
    public String mcyzJy(String bjdID) throws Exception {
        String fhjg = "", freecopies = "";
        List<CCObject> bjdlist=cs.cqlQuery("quote","select freecopies from quote where is_deleted='0' and id='"+bjdID+"'");//报价单
        if (bjdlist.size() > 0) {
            freecopies = bjdlist.get(0).get("freecopies")==null?"":bjdlist.get(0).get("freecopies").toString();//是否送免费印张
        }
        if ("true".equals(freecopies)) {
            List<CCObject> bjdmlist=cs.cqlQuery("quotedetail","select * from quotedetail where is_deleted='0' and bjdmc='"+bjdID+"' and mcid is not null");
            if (bjdmlist.size() == 0) {
                fhjg = "提交失败，该报价中没有MC信息，不可勾选是否送免费印张！";
            }
        }
        return fhjg;
    }
    
    /**
     * 林贵美 2019-03-20创建
     * 方法名：selectTjsq
     * 校验该报价特价申请是否审批通过
     **/
    public String selectTjsq(String bjdID) throws Exception {
        List<CCObject> bjdlist=cs.cqlQuery("quote","select specialapplication from quote where is_deleted='0' and id='"+bjdID+"'");//报价单
        String fh = "";
        if (bjdlist.size() > 0) {
            String specialapplication = bjdlist.get(0).get("specialapplication")==null?"":bjdlist.get(0).get("specialapplication").toString();//特价申请
            List<CCObject> applyforspecialList=cs.cqlQuery("applyforspecial","select cbhsspzt from applyforspecial where is_deleted='0' and id='"+specialapplication+"'");//特价申请
            if (applyforspecialList.size() > 0) {
                String cbhsspzt = applyforspecialList.get(0).get("cbhsspzt")==null?"":applyforspecialList.get(0).get("cbhsspzt").toString();//审批状态
                if (!"审批通过".equals(cbhsspzt)) {
                    fh = "特价申请还未审批通过，无法提交！";
                }
            }
        }
        return fh;
    }
     /**
     * author ：林贵美 on 2019-08-27
     * 提交/打印/同步报价，以及生成特价申请时，新加验证，判断套类明细中是否有售价=0以下（包括0）的货品，
     * 有则提交/打印/同步报价，以及生成特价申请时，失败，然后提示。
     * 
     * 返回：JSON； 结果编码：成功（S）/失败（E+“3位编码”）
     * 方法调用位置：1）本类的selectPrice方法；2）报价生成特价申请页面。
     */
    public JSONObject bjtlmxSjVerification (String bjid) {
        JSONObject rtnInfo = new JSONObject();
        rtnInfo.put("SuccessFlag", "S");
        rtnInfo.put("ErrorMessage", "");

        try {
            List<CCObject> packageproductsList = cs.cquery("packageproducts","quotationnumber='"+bjid+"' and salesunitprice<=0");//报价单套类产品明细
            if (packageproductsList.size() > 0) {
                rtnInfo.put("SuccessFlag", "E007");
                rtnInfo.put("ErrorMessage", "套类货品明细销售单价需大于0，请核查！");
                rtnInfo.put("ReturnData", "");
                return rtnInfo;
            }
            
            String sql = "select t1.id,t1.cpdm,round(t1.xsjg,2) xsjg,round(sum(t0.salesunitprice*t0.amount),2)  as  totalprice from packageproducts t0,quotedetail t1"
            		+ " where t0.is_deleted='0' and t1.is_deleted='0' and t0.sstlbh=t1.id and t1.bjdmc='"+bjid+"' group by t1.id,t1.cpdm";
            List<CCObject> setItemLists = cs.cqlQuery("packageproducts", sql);
            for (CCObject item : setItemLists) {
            		String xsjg = String.valueOf(item.get("xsjg"));
            		String totalprice = String.valueOf(item.get("totalprice"));
            		BigDecimal xsjg_b = new BigDecimal(xsjg);
            		BigDecimal totalprice_b = new BigDecimal(totalprice);
            		if (xsjg_b.compareTo(totalprice_b) != 0) {
            			rtnInfo.put("SuccessFlag", "E007");
                    rtnInfo.put("ErrorMessage", "货品"+item.get("cpdm")+"的销售单价(xsjg)与该套类明细货品的价格累加(totalprice)不符，请检查");
                    rtnInfo.put("ReturnData", "");
                    break;
            		}
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            rtnInfo.put("SuccessFlag", "E007");
            rtnInfo.put("ErrorMessage", "处理出现异常.请联系管理员获取支持,错误号：E007");
            rtnInfo.put("ReturnData", "");
        }

        return rtnInfo;
    }
    /**
     * author 林贵美 Founded on 2019-09-20
     * 方法名：freepapertotalVerification
     * bjdId【报价单ID】
     * 目的：
     *      提交/打印/同步报价时，新加验证，关于报价的免印 与 明细引用的特价的免印；
     * 逻辑：
     *      整单：当前报价的免印小计 > 特价申请的免印小计 == 失败
     * 调用位置：本类selectPrice方法
     */
    public JSONObject freepapertotalVerification (String bjdId) {
        JSONObject rtnInfo = new JSONObject();
        rtnInfo.put("SuccessFlag", "S");
        rtnInfo.put("ErrorMessage", "");
        try {
            String quoteSql  = "select t0.cfreepaperprice as bjcsjg,t0.cfreepaperqty as bjcssl, ";
                   quoteSql += "       t0.bfreepaperprice as bjhbjg,t0.bfreepaperqty as bjhbsl, ";
                   quoteSql += "       t1.cfreepaperprice as tjcsjg,t1.cfreepaperqty as tjcssl, ";
                   quoteSql += "       t1.bfreepaperprice as tjhbjg,t1.bfreepaperqty as tjhbsl ";
                   quoteSql += "  from quote t0 ,applyforspecial t1 ";
                   quoteSql += " where t1.is_deleted='0' ";
                   quoteSql += "   and t1.id=t0.specialapplication ";
                   quoteSql += "   and t0.id='"+bjdId+"' ";
                   quoteSql += "   and t0.discounttype='整单' ";
                   quoteSql += "   and t0.is_deleted='0' ";
            List<CCObject> quoteList = cs.cqlQuery("quote", quoteSql);//报价单
            if (quoteList.size() > 0) {
                String bjcsjg = quoteList.get(0).get("bjcsjg")==null?"0.00":quoteList.get(0).get("bjcsjg").toString();//彩色价格-报价
                String bjcssl = quoteList.get(0).get("bjcssl")==null?"0":quoteList.get(0).get("bjcssl").toString();//彩色数量-报价
                String bjhbjg = quoteList.get(0).get("bjhbjg")==null?"0.00":quoteList.get(0).get("bjhbjg").toString();//黑白价格-报价
                String bjhbsl = quoteList.get(0).get("bjhbsl")==null?"0":quoteList.get(0).get("bjhbsl").toString();//黑白数量-报价
                String tjcsjg = quoteList.get(0).get("tjcsjg")==null?"0.00":quoteList.get(0).get("tjcsjg").toString();//彩色价格-特价
                String tjcssl = quoteList.get(0).get("tjcssl")==null?"0":quoteList.get(0).get("tjcssl").toString();//彩色数量-特价
                String tjhbjg = quoteList.get(0).get("tjhbjg")==null?"0.00":quoteList.get(0).get("tjhbjg").toString();//黑白价格-特价
                String tjhbsl = quoteList.get(0).get("tjhbsl")==null?"0":quoteList.get(0).get("tjhbsl").toString();//黑白数量-特价
                Double bjcsmyDou = Double.parseDouble(bjcsjg)*Double.parseDouble(bjcssl);//彩色免印-报价
                Double bjhbmyDou = Double.parseDouble(bjhbjg)*Double.parseDouble(bjhbsl);//黑白免印-报价
                Double tjcsmyDou = Double.parseDouble(tjcsjg)*Double.parseDouble(tjcssl);//彩色免印-特价
                Double tjhbmyDou = Double.parseDouble(tjhbjg)*Double.parseDouble(tjhbsl);//黑白免印-特价
                
                if ((bjcsmyDou+bjhbmyDou) > (tjcsmyDou+tjhbmyDou)) {
                    rtnInfo.put("SuccessFlag", "E008");
                    rtnInfo.put("ErrorMessage", "报价免印总计不可大于特价免印总计，请检查！");
                    rtnInfo.put("ReturnData", "");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            rtnInfo.put("SuccessFlag", "E008");
            rtnInfo.put("ErrorMessage", "处理出现异常.请联系管理员获取支持,错误号：E008");
            rtnInfo.put("ReturnData", "");
        }
        return rtnInfo;
    }
    /**
     * 林贵美 2019-03-27创建
     * 方法名：selectPrice
     * 若报价单明细中，销售单价小于标准销售价格，但报价单中没有引用特价申请，则不能提交报价
     * 若报价包含免印，无论是否销售价格低于标准售价，都需要申请特价
     **/
    public String selectPrice(String bjdID) throws Exception {
        List<CCObject> bjdlist=cs.cqlQuery("quote","select recordtype,specialapplication,freecopies from quote where is_deleted='0' and id='"+bjdID+"'");//报价单
        String fh = "";
        if (bjdlist.size() > 0) {
            boolean xy = false;
            boolean sfmz = false;//是否满足MC
            List<CCObject> quotemxList=cs.cqlQuery("quotedetail","select standardsalesprice,xsjg,mcid,chanpin,cpdm,discountno from quotedetail where is_deleted='0' and bjdmc='"+bjdID+"'");//报价单明细
            for (int q=0; q<quotemxList.size(); q++) {
                String standardsalesprice = quotemxList.get(q).get("standardsalesprice")==null?"0.00":quotemxList.get(q).get("standardsalesprice").toString();//标准
                String xsjg = quotemxList.get(q).get("xsjg")==null?"0.00":quotemxList.get(q).get("xsjg").toString();//销售
                String mcid = quotemxList.get(q).get("mcid")==null?"":quotemxList.get(q).get("mcid").toString();//对应MC
                String cpdm = quotemxList.get(q).get("cpdm")==null?"":quotemxList.get(q).get("cpdm").toString();//产品代码
                String chanpin = quotemxList.get(q).get("chanpin")==null?"":quotemxList.get(q).get("chanpin").toString();//货品ID
                String discountno = quotemxList.get(q).get("discountno")==null?"":quotemxList.get(q).get("discountno").toString();//特价可决号
                String specialapplication = bjdlist.get(0).get("specialapplication")==null?"":bjdlist.get(0).get("specialapplication").toString();//特价申请
                String jllx = bjdlist.get(0).get("recordtype")==null?"":bjdlist.get(0).get("recordtype").toString();//记录类型
                if (!"".equals(discountno)) {
	            		specialapplication = discountno;
	            }
                //根据特价可决号，查询产品销售价格是否低于特价申请价格
                String queryCondition = " select t0.id,t0.name,t1.salesunitprice,t1.mcinformation from applyforspecial t0,itemsofspecialapply t1 " + 
									" where t1.productname='"+chanpin+"'"+
									" and t1.parentid=t0.id "+
									" and t0.id='" + specialapplication + "'" + 
									" and t0.is_deleted='0' and t1.is_deleted='0'";
                logger.info("function selectPrice:queryCondition:"+queryCondition);
                List<CCObject> applyforspecialList=cs.cqlQuery("applyforspecial",queryCondition);//特价申请
                BigDecimal xsjg_d = new BigDecimal(xsjg);
                BigDecimal bzjg_d = new BigDecimal(standardsalesprice);
	            if (xsjg_d.compareTo(bzjg_d)==-1) {
	                xy = true;//是否需要特价
	            }else {
                       xy = false;
                   }
	            
                if ("201892641642AA3N0gDf".equals(jllx)) {//货品报价
                    if (applyforspecialList.size() == 0) {
	                    	if (xy) {
	                    		fh = cpdm+"销售单价"+ xsjg +"小于标准销售价格，请先申请特价！";
	                    		return fh;
	                    	}
                               if ("true".equals(bjdlist.get(0).get("freecopies"))) {
	                    		fh = "报价包含免费印张,请先申请特价！";
	                    		return fh;
	                     }
                    } else {
	                    	//特价申请销售价格
	                    	String discount_salesprice_str = (String)applyforspecialList.get(0).get("salesunitprice");
	                    	if (discount_salesprice_str != null && !"".equals(discount_salesprice_str)) {
	                    		BigDecimal discount_salesprice = new BigDecimal(discount_salesprice_str);
	                    		BigDecimal quote_salesprice = new BigDecimal(xsjg);
	                    		if (discount_salesprice.compareTo(quote_salesprice)==1) {//特价申请价格大于报价单销售价格
	                    			fh = cpdm+"销售单价小于特价申请价格"+discount_salesprice_str+"，请修改销售价格！";
	                    			return fh;
	                    		}
	                    	}
                    }
                }
                
                if (mcid != null && !"".equals(mcid)) {
                    sfmz = mcVerify(mcid,chanpin,specialapplication);
                    if (sfmz) {
                    	 fh = "Mc价格低于标准价格，请先申请特价！";
                    	 return fh;
                    }
                }
            }
        }
        /**
         * author ：林贵美 on 2019-08-27
         * 提交/打印/同步报价，以及生成特价申请时，新加验证，判断套类明细中是否有售价=0以下（包括0）的货品，
         * 有则提交/打印/同步报价，以及生成特价申请时，失败，然后提示。
         */
        JSONObject rst = bjtlmxSjVerification (bjdID);	
	String SuccessFlag = rst.get("SuccessFlag").toString();
        if ("E007".equals(SuccessFlag)) {
            fh = rst.get("ErrorMessage").toString();
        }
        /**
         * author 林贵美 Founded on 2019-09-20
         * 提交/打印/同步报价时，新加验证，关于报价的免印 与 明细引用的特价的免印；
         */
        JSONObject rstMy = freepapertotalVerification (bjdID);	
        String SuccessFlagMy = rstMy.get("SuccessFlag").toString();
        if ("E008".equals(SuccessFlagMy)) {
            fh = rstMy.get("ErrorMessage").toString();
        }
        return fh;
    }
    
    /**
     * 校验mc信息是否需要申请特价
     * @author caoyx 2019.6.6
     * @param mcid MCId
     * @param productid产品ID
     * @param discountId 特价ID
     * 对于MC信息，判断是否要走特价的条件： 
        ①、若输入的超张费(售价) < 取得的特价申请底价(mcpricemaster.SalesBottomlinePrice)                                                                                                                                                                                                 
        ②、若输入的基本费的售价 < 取得的基本费的标价（mcpricemaster.BasicalFee）                                                                                         
        若输入的包含张数特别 >0的场合:                                                                                                                                                         
        ③、若输入的基本费的售价/输入的包含张数特别 < 取得的基本费的标价（mcpricemaster.BasicalFee）/取得的包含张数标准 （mcpricemaster.IncludedPaperQty）                                                                                                                                                         
		上述①、②、③有一种情况存在，则MC则需要走特价。 
     * @return
     */
    public boolean mcVerify (String mcid,String productid,String discountId) {
    		boolean flag = false;
    		BigDecimal zero = new BigDecimal(0);
    		List<CCObject> discountItems = cs.cquery("itemsofspecialapply","parentid='"+discountId+"' and productname='"+productid+"'");
    		String discount_mcno = "";
    		List<CCObject> discountMcItems = null;
    		if (discountItems.size() > 0) {
    			discount_mcno = (String)discountItems.get(0).get("mcinformation");
    			String sql = "select t.mcno,t.salespaperqty,t.cgjbfwdj,t1.chargetype mcchargetype,t.salesprice,t.salesfee from mcgrade t,mcbaseinfo t1 where t.mcno=t1.id and t1.name='"+discount_mcno+"' and t.is_deleted='0' and t1.is_deleted='0'";
    			logger.info("function mcVerify:sql:"+sql);
    			discountMcItems = cs.cqlQuery("mcbaseinfo",sql);
    			if (discountMcItems.size() > 0) {
    				String discountMcId = (String)discountMcItems.get(0).get("mcno");
    				if (mcid.equals(discountMcId)) {
    					return false;
    				}
    			}
    		}
    		List<CCObject> gradeItemList = cs.cquery("mcgrade","mcno='"+mcid+"'");
    		//判断包张、销售价格、超张费、基本费是否大于特价Mc申请信息
    		if (discountMcItems != null && discountMcItems.size()>0) {
    			for (CCObject discountMcItem : discountMcItems) {
    				String dct_mcchargetype = (String) discountMcItem.get("mcchargetype");
    				String dct_metertype = (String) discountMcItem.get("metertype");
    				String dct_cgjbfwdj = (String) discountMcItem.get("cgjbfwdj");//超过基本费外等级
    				String dct_paper = discountMcItem.get("salespaperqty") == null || "".equals(discountMcItem.get("salespaperqty")) ? "0" : (String)discountMcItem.get("salespaperqty");
    				String dct_unitprice = discountMcItem.get("salesprice") == null || "".equals(discountMcItem.get("salesprice")) ? "0.00" : (String)discountMcItem.get("salesprice");
    				String dct_basicalfee = discountMcItem.get("salesfee") == null || "".equals(discountMcItem.get("salesfee")) ? "0.00" : (String)discountMcItem.get("salesfee");
				
    				BigDecimal dct_paper_bd = new BigDecimal(dct_paper);
    				BigDecimal dct_unitprice_bd = new BigDecimal(dct_unitprice);
    				BigDecimal dct_basicalfee_bd = new BigDecimal(dct_basicalfee);
    				
    				for (CCObject gradeItem : gradeItemList) {
    					String metertype = (String) gradeItem.get("metertype");//计费项目如黑白A4
    					String mcchargetype = (String) gradeItem.get("mcchargetype");//计费项目如黑白A4
    					String cgjbfwdj = (String) gradeItem.get("cgjbfwdj");//超过基本费外等级
    					if (metertype != null && metertype.equals(dct_metertype)) {
    						if (mcchargetype != null && mcchargetype.equals(dct_mcchargetype)) {
    							if (cgjbfwdj != null && cgjbfwdj.equals(dct_cgjbfwdj)) {
    								String salespaperqty = (String)gradeItem.get("salespaperqty");//包含张数（特别）
    								BigDecimal paper_sales = new BigDecimal(0);
    								if (salespaperqty != null && !"".equals(salespaperqty)) {
	    				    				paper_sales = new BigDecimal(salespaperqty);
	    				    			}
    								
    								String salesprice = (String)gradeItem.get("salesprice");//超张费（售价）
    								BigDecimal unitprice_sales = new BigDecimal(0);
    								if (salesprice != null && !"".equals(salesprice)) {
	    				    				unitprice_sales = new BigDecimal(salesprice);
	    				    			}
    								
    								String salesfee = (String)gradeItem.get("salesfee");//基本费(售价)
    								BigDecimal basicalfee_sales = new BigDecimal(0);
    								if (salesfee != null && !"".equals(salesfee)) {
	    				    				basicalfee_sales = new BigDecimal(salesfee);
	    				    			}
    								
    								if (paper_sales.compareTo(dct_paper_bd) == -1) {
    									return true;
    								}
    								
    								if (unitprice_sales.compareTo(dct_unitprice_bd) == -1) {
    									return true;
    								}
    								
    								if (basicalfee_sales.compareTo(dct_basicalfee_bd) == -1) {
    									return true;
    								}
    							}
    						}
    					}
    				}
    			}
    		} else {
	    		//如mc没有申请过特价，那么需要验证Mc需要不需要走特价
	    		for (CCObject item : gradeItemList) {
	    			String salespaperqty = (String)item.get("salespaperqty");//包含张数（特别）
	    			String includedpaperqty = (String)item.get("includedpaperqty");//包含张数（标准）
	    			
	    			BigDecimal paper_sales = new BigDecimal(0);
	    			BigDecimal paper_standard = new BigDecimal(0);
	    			if (salespaperqty != null && !"".equals(salespaperqty)) {
	    				paper_sales = new BigDecimal(salespaperqty);
	    			}
	    			if (includedpaperqty != null && !"".equals(includedpaperqty)) {
	    				paper_standard = new BigDecimal(includedpaperqty);
	    			}
	    			
	    			if (paper_standard.compareTo(zero) == 0 && paper_sales.compareTo(zero) == 1) {
	    				//如果标准没有包张，销售有包张，需要走特价.
	    				flag = true;
	    				return flag;
	    			}
	    			
	    			/** 条件①验证**/
	    			String salesprice = (String)item.get("salesprice");//超张费（售价）
	    			String salesbottomlineprice = (String)item.get("salesbottomlineprice");//特价申请底价
	    			BigDecimal unitprice_sales = new BigDecimal(0);
	    			BigDecimal unitprice_bottom = new BigDecimal(0);
	    			if (salesprice != null && !"".equals(salesprice)) {
	    				unitprice_sales = new BigDecimal(salesprice);
	    			}
	    			if (salesbottomlineprice != null && !"".equals(salesbottomlineprice)) {
	    				unitprice_bottom = new BigDecimal(salesbottomlineprice);
	    			}
	    			
	    			if (unitprice_sales.compareTo(unitprice_bottom) == -1) {
	    				flag = true;
	    				return flag;
	    			}
	    			
	    			/** 条件②验证**/
	    			String basicalfee = (String)item.get("basicalfee");//基本费(标准)
	    			String salesfee = (String)item.get("salesfee");//基本费（售价）
	    			BigDecimal basicalfee_sales = new BigDecimal(0);
	    			BigDecimal basicalfee_standard = new BigDecimal(0);
	    			if (basicalfee != null && !"".equals(basicalfee)) {
	    				basicalfee_standard = new BigDecimal(basicalfee);
	    			}
	    			if (salesfee != null && !"".equals(salesfee)) {
	    				basicalfee_sales = new BigDecimal(salesfee);
	    			}
	    			if (basicalfee_sales.compareTo(basicalfee_standard) == -1) {
	    				flag = true;
	    				return flag;
	    			}
	    			
	    			/** 条件③验证**/
	    			if (paper_standard.compareTo(zero) == 1 && paper_sales.compareTo(zero) == 1) {
	    				//包张单价
	    				BigDecimal unitprice_paper_sales = basicalfee_sales.divide(paper_sales,4,BigDecimal.ROUND_CEILING);
	    				BigDecimal unitprice_paper_standard = basicalfee_standard.divide(paper_standard,4,BigDecimal.ROUND_CEILING);
	    				if (unitprice_paper_sales.compareTo(unitprice_paper_standard) == -1) {
	    					flag = true;
	        				return flag;
	    				}
	    			}
	    		}
    		}
    		
    		return flag;
    }
    
    /**
     * 林贵美 2019-04-15创建
     * 方法名：mcVerification
     **/
    public boolean mcVerification(String mcid) throws Exception {
        boolean sfmz = false;
        String chargetype = "";
        List<CCObject> mcList = cs.cqlQuery("mcbaseinfo","select chargetype,itemdescription from mcbaseinfo where is_deleted='0' and id='"+mcid+"'");
        List<CCObject> mcItemList = new ArrayList<CCObject>();
        CCObject mcInfo = new CCObject();
        String productid = "";
        if (mcList.size() > 0) {
            mcInfo = mcList.get(0);
            chargetype = (String)mcInfo.get("chargetype");
            mcItemList = cs.cquery("mcgrade","mcno='"+mcid+"'");
            productid = mcList.get(0).get("itemdescription")==null?"":mcList.get(0).get("itemdescription").toString();//货品
        } 
        String sql = "descriptionofgoods='"+productid+"' and chargetype='" + chargetype + "'";
        List<CCObject> mcInfoList = cs.cquery("mcmasterdata",sql);
        List<CCObject> mcgradeList = new ArrayList<CCObject> ();
        if (mcInfoList.size() > 0) {
            mcgradeList = cs.cquery("mcdetailinformatio","productname='" + productid + "' and chargetype='"+chargetype+"'");
        }
        
        for(CCObject mc : mcInfoList) {
            String mcmainid = (String)mc.get("id");
            String basicfee = "";
            String containnumber = "";
            String salesprice = "";
            for (CCObject item : mcgradeList) {
                String itemid = (String)item.get("id");
                String mcmasternumber = (String)item.get("mcmasternumber");
                String item_endofstartinginterval = (String)item.get("endofstartinginterval");
                String item_startingintervalbegins = (String)item.get("startingintervalbegins");
                String item_metertype = (String)item.get("metertype");
                if (!mcmainid.equals(mcmasternumber)) {
                  continue;
                }
                basicfee = (String) mc.get("basicfee");
                containnumber = (String) mc.get("containnumber");
                salesprice = (String) item.get("standardprice");
                for (CCObject mcItem : mcItemList) {
                    String mcitem_metertype = (String)mcItem.get("metertype");
                    String mcitem_startqty = (String)mcItem.get("startqty");
                    String mcitem_endqty = (String)mcItem.get("endqty");
                    if (item_metertype.equals(mcitem_metertype) && mcitem_startqty.equals(item_startingintervalbegins)
                    &&mcitem_endqty.equals(item_endofstartinginterval)) {
                        basicfee = (String) mcItem.get("salesfee");
                        containnumber =  mcItem.get("salespaperqty")==null?"0":mcItem.get("salespaperqty").toString();
                        salesprice = (String) mcItem.get("salesprice");
                    }
                }
              
                double yjbsjDou = Double.parseDouble(basicfee);//月基本费售价
                double yjbbzDou = Double.parseDouble(mc.get("basicfee").toString());//月基本费标准
                double bhzqyDou = Double.parseDouble(containnumber);//包含张数签约
                double bhzbzDou = Double.parseDouble(mc.get("containnumber").toString());//包含张数标准
                double sjyDou = Double.parseDouble(salesprice);//售价（元）
                double bjyDou = Double.parseDouble(item.get("standardprice").toString());//标价（元）

                //报价明细-MC是否适合
                if (((yjbsjDou/bhzqyDou) < (yjbbzDou/bhzbzDou)) || (sjyDou<bjyDou)) {
                    sfmz = true;
                } else {
                    sfmz = false;
                }
            }
        }
        return sfmz;
    }
    
    /**
     * 林贵美 2019-04-08创建
     * 方法名：mcyzJy
     * 特价申请-提交待审批：校验是否有mc服务，如果没有MC，但是填写了免印信息，不允许提交报价
     **/
    public String tjmcyzJy(String tjsqID) throws Exception {
        String fhjg = "", freecopyflg = "";
        List<CCObject> applyforspeciallist=cs.cqlQuery("applyforspecial","select freecopyflg from applyforspecial where is_deleted='0' and id='"+tjsqID+"'");//特价申请
        if (applyforspeciallist.size() > 0) {
            freecopyflg = applyforspeciallist.get(0).get("freecopyflg")==null?"":applyforspeciallist.get(0).get("freecopyflg").toString();//是否送免费印张
        }
        if ("true".equals(freecopyflg)) {
            List<CCObject> tjsqmlist=cs.cquery("itemsofspecialapply","parentid='"+tjsqID+"' and mcinformation is not null");
            if (tjsqmlist.size() == 0) {
                fhjg = "提交待审批失败，该特价中没有MC信息，不可勾选是否送免费印张！";
            }
        }
        return fhjg;
    }
    
    /**
     * 林贵美 2019-04-11
     * 没有货品明细时，不可提交报价
     */
    public String hpmxJy(String bjdID) throws Exception {
        List<CCObject> quotedetailList = cs.cqlQuery("quotedetail", "select * from quotedetail where is_deleted='0' and bjdmc='"+bjdID+"'");//报价单明细
        String fhjg = "";
        if (quotedetailList.size() == 0) {
            fhjg = "该报价没有报价货品明细，不可提交报价！";
        }
        return fhjg;
    }
    
    /**
     * 林贵美 2019-04-12
     * 报价单免印信息验证
     * 1）“黑白免印数量” or “彩色免印单价” or “彩色免印数量” or “黑白免印单价”，有填写时，必须选择“是否送免费印张”
     * 2）勾选是否免印：黑白单价不可为0，数量不可为空
     * 3）数量只能填自然数
     * 4）报价中没有MC信息，不可勾选是否送免费印张
     *
     * 返回：JSON； 结果编码：成功（S）/失败（E+“3位编码”）
     */
    public JSONObject bjdmyVerification (String freecopies, String bfreepaperqty, String bfreepaperprice,String cfreepaperqty, 
                                         String cfreepaperprice, String jlid, String jlType) {
        JSONObject rtnInfo = new JSONObject();
        rtnInfo.put("SuccessFlag", "S");
        rtnInfo.put("ErrorMessage", "");
        try {
            if ("".equals(freecopies) || "false".equals(freecopies)) {
                cfreepaperqty = "0.00";
                if (Double.parseDouble(bfreepaperqty) > 0 || Double.parseDouble(bfreepaperprice) > 0 || 
                    Double.parseDouble(cfreepaperqty) > 0 || Double.parseDouble(cfreepaperprice) > 0) {
                    rtnInfo.put("SuccessFlag","E001");
                    rtnInfo.put("ErrorMessage","请勾选是否送免费印张！");
                }
            } else {
                //勾选是否免印：黑白单价不可为0，数量不可为空
                /*if (Double.parseDouble(bfreepaperprice) <= 0) {
                    rtnInfo.put("SuccessFlag","E002");
                    rtnInfo.put("ErrorMessage","黑白免印单价不可为0！");
                }
                if (Double.parseDouble(bfreepaperqty) == 0) {
                    rtnInfo.put("SuccessFlag","E003");
                    rtnInfo.put("ErrorMessage","请填写黑白免印数量！");
                }*/
                if (Double.parseDouble(bfreepaperqty) == 0 && Double.parseDouble(bfreepaperprice) == 0 && 
                    Double.parseDouble(cfreepaperqty) == 0 && Double.parseDouble(cfreepaperprice) == 0) {
                    rtnInfo.put("SuccessFlag","E001");
                    rtnInfo.put("ErrorMessage","已勾选是否送免费印张，请填写免印信息！");
                }
                
                if (!"".equals(cfreepaperqty)) {
                    //数量不可填负数
                    if (Double.parseDouble(bfreepaperqty) < 0) {
                        rtnInfo.put("SuccessFlag","E004");
                        rtnInfo.put("ErrorMessage","保存失败，黑白免印数量不可小于0！");
                    }
                }

                if (!"".equals(cfreepaperqty)) {
                    if (Double.parseDouble(cfreepaperqty) < 0) {
                        rtnInfo.put("SuccessFlag","E005");
                        rtnInfo.put("ErrorMessage","保存失败，彩色免印数量不可小于0！");
                    }
                }
                //报价中没有MC信息，不可勾选是否送免费印张
                /*if ("insert".equals(jlType)) {
                        rtnInfo.put("SuccessFlag","E006");
                        rtnInfo.put("ErrorMessage","该报价中没有MC信息，不可勾选是否送免费印张！");
                } else {
                    List<CCObject> bjdmlist=cs.cquery("quotedetail","bjdmc='"+jlid+"' and mcid is not null");
                    if (bjdmlist.size() == 0) {
                        rtnInfo.put("SuccessFlag","E006");
                        rtnInfo.put("ErrorMessage","该报价中没有MC信息，不可勾选是否送免费印张！");
                    }
                }*/
            }
        } catch (Exception ex) {
			ex.printStackTrace();
			rtnInfo.put("SuccessFlag", "E007");
			rtnInfo.put("ErrorMessage", "报价单验证过程中出现异常，请联系管理员获取支持，错误号：E007");
			rtnInfo.put("ReturnData", "");
		}
        return rtnInfo;
    }

    /**
     * LG 2019-04-11
     * 提交审批前判断当前特价申请下的MC信息是否都填写"月估印量"
     */
	
	 public String yzygyl(String tjid) throws Exception {
		String msg="";
		List<CCObject> mcinfoList =cs.cquery("mcinfo","parentid='"+tjid+"'");//特价MC信息
		for(CCObject mclist : mcinfoList){
			String ygyl=mclist.get("monthlyprintamount")==null?"0":mclist.get("monthlyprintamount").toString();
			String mcname=mclist.get("name")==null?"":mclist.get("name").toString();
			if(Double.valueOf(ygyl)<=0){
				msg="MC信息中明细编号为："+mcname+"的mc信息未填写月估印量，无法提交审批。";
			}
		}
		return msg;
	}
    /**
     * 林贵美 2019-05-10
     * bug410 问题描述：特价申请可以被其他客户的报价单引用
     *        处理方式：报价单保存的时候验证报价单的项目名称和特价申请对应的项目名称是否一致。
     *
     * 返回：JSON； 结果编码：成功（S）/失败（E+“3位编码”）
     */
    public JSONObject ApplyforspecialVerification (String bjYwjhId, String tjsqId) {
        JSONObject rtnInfo = new JSONObject();
        rtnInfo.put("SuccessFlag", "S");
        rtnInfo.put("ErrorMessage", "");
        try {
            CCObject applyforspecialinfo = new CCObject("applyforspecial");
            List<CCObject> applyforspecialList = cs.cquery("applyforspecial","id='"+tjsqId+"'");//特价申请
            if (applyforspecialList.size() > 0) {
                applyforspecialinfo = applyforspecialList.get(0);
                String ywjhmc = applyforspecialinfo.get("ywjhmc")==null?"":applyforspecialinfo.get("ywjhmc").toString();//特价-业务机会
                String applicationtype = applyforspecialinfo.get("applicationtype")==null?"":applyforspecialinfo.get("applicationtype").toString();//特价-业务机会
                if (!ywjhmc.equals(bjYwjhId) && !"集团".equals(applicationtype)) {
                    rtnInfo.put("SuccessFlag", "E002");
                    rtnInfo.put("ErrorMessage", "该报价的项目名称 与 特价的项目名称不一致，保存失败！");
                    rtnInfo.put("ReturnData", "");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            rtnInfo.put("SuccessFlag", "E001");
            rtnInfo.put("ErrorMessage", "申请特价过程中出现异常.请联系管理员获取支持,错误号：E001");
            rtnInfo.put("ReturnData", "");
        }
        return rtnInfo;
    }
    /**
     * 检查报价单对应项目的合同进展状态是否完成，如果未完成就可以修改价格，并且价格不能低于特价申请价格
     * Delbug 611
     * @param quoteId
     * @return
     */
    public JSONObject editingCheck(String quoteId) {
    		JSONObject rtnMsg = new JSONObject();
    		rtnMsg.put("successFlag", "True");
		rtnMsg.put("Message", "");
    		String sql = "select o.contractstatus,o.id,q.submitflag from Opportunity o,quote q where o.id=q.ywjhmc and q.id='" + quoteId + "'";
    		List<CCObject> oppList = cs.cqlQuery("Opportunity", sql);
    		if (oppList.size() > 0) {
    			String contractstatus = (String)oppList.get(0).get("contractstatus");
    			if ("完成".equals(oppList.get(0).get("contractstatus"))) {
    				rtnMsg.put("successFlag", "False");
    				rtnMsg.put("Message", "合同状态已完成，请勿提交或修改报价单");
    				return rtnMsg;
    			} else {
    				Date now = new  Date();
    				SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
    				String token = MD5.MD5Encode("GetCaseContractStatus"+sdf.format(now)+"cloudcccrm");
    				try {
    					String str = "serviceName=GetCaseContractStatus&timestamp="+sdf.format(now)+"&verifyCode="+token+"&data={\"CaseNo\":\""+contractstatus+"\"}";
    					String rst = OperationService.operate("http://dcm.ricoh.com.cn:9082/ricohcrmdev/distributor.action", str);
    					JSONObject callRst = JSONObject.fromObject(rst);
    					String SuccessFlag = (String)callRst.get("SuccessFlag");
    					if(!"1".equals(SuccessFlag)) {
    						rtnMsg.put("successFlag", "False");
		    				rtnMsg.put("Message", callRst.get("ErrorMessage"));
		    				return rtnMsg;
    					}
    					if (callRst.containsKey("ReturnData")) {
    						JSONObject rtnData = callRst.getJSONObject("ReturnData");
    						String contStatus = (String)rtnData.get("ContStatus");
    						sql = "update Opportunity o,quote q set o.contractstatus='" + contStatus + "' where o.id=q.ywjhmc and q.id='" + quoteId + "'";
    						cs.cqlQuery("Opportunity", sql);
    						if ("完成".equals(contStatus)) {
	    		    				rtnMsg.put("successFlag", "False");
	    		    				rtnMsg.put("Message", "合同状态已完成，请勿提交或修改报价单");
	    		    				return rtnMsg;
	    		    			}
    					}
    				} catch (Exception e) {
    					rtnMsg.put("successFlag", "False");
	    				rtnMsg.put("Message", "获取合同状态错误，请联系管理员");
	    				return rtnMsg;
    				}
    			}
//    			if ("true".equals(oppList.get(0).get("submitflag"))) {
//    				rtnMsg.put("successFlag", "False");
//    				rtnMsg.put("Message", "报价单已提交，请勿修改报价单");
//    			}
    		} else {
    			rtnMsg.put("successFlag", "False");
    			rtnMsg.put("Message", "未查到报价单的所属项目信息");
    			return rtnMsg;
    		}
    		sql = "select t1.cbhsspzt,t1.id,t1.name from applyforspecial t1,quote t2 where t1.id=t2.specialapplication and t2.id='" + quoteId + "'";
    		List<CCObject> discountList = cs.cqlQuery("applyforspecial", sql);
    		if (discountList.size() > 0) {
    			if ("审批中".equals(discountList.get(0).get("cbhsspzt"))) {
    				rtnMsg.put("successFlag", "False");
    				rtnMsg.put("Message", "特价"+discountList.get(0).get("name")+"审批中，不能修改报价");
    			}
    		}
    		return rtnMsg;
    }
    /**
    public static void main(String[] args) {
    		ResourceBundle prb = PropertyResourceBundle.getBundle("conf");// 获取配置文件
    		UserInfo uInfo = new UserInfo();
		uInfo.put("userName",prb.getString("userName"));
		uInfo.put("password", prb.getString("password"));
		QuoteVerification qv = new QuoteVerification(uInfo);
		try {
			qv.selectPrice("0112019A5018FB54npvY");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	**/
}